package top.forforever.srb.core.controller.api;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.forforever.srb.common.exception.Assert;
import top.forforever.srb.common.result.R;
import top.forforever.srb.common.result.ResponseEnum;
import top.forforever.srb.core.hfb.RequestHelper;
import top.forforever.srb.core.service.TransFlowService;
import top.forforever.srb.core.service.UserAccountService;
import top.forforever.srb.core.util.AuthContextHolder;

import javax.servlet.http.HttpServletRequest;
import javax.xml.crypto.dsig.TransformService;
import java.math.BigDecimal;
import java.util.Map;

/**
 * <p>
 * 用户账户 前端控制器
 * </p>
 *
 * @author Mr.Jiang
 * @since 2023-04-29
 */
@RestController
@RequestMapping("/api/core/userAccount")
public class ApiUserAccountController {

    @Autowired
    private UserAccountService userAccountService;

    @Autowired
    private TransFlowService transFlowService;

    @GetMapping("getAccount")
    public R getAccount(HttpServletRequest request) {
        Long userId = AuthContextHolder.getUserIdAndAuth(request);
        BigDecimal account = userAccountService.getAccount(userId);
        return R.ok().data("account", account);
    }

    @GetMapping("commitCharge/{chargeAmt}")
    public R commitCharge(@PathVariable BigDecimal chargeAmt, HttpServletRequest request) {
        Long userId = AuthContextHolder.getUserIdAndAuth(request);
        String form = userAccountService.commitCharge(chargeAmt, userId);
        return R.ok().data("form", form);
    }

    //充值回调接口
    @PostMapping("notify")
    public String rechargeNotify(HttpServletRequest request) {
        Map<String,String[]> parameterMap = request.getParameterMap();
        Map<String, Object> switchMap = RequestHelper.switchMap(parameterMap);
        //添加幂等性判断，防止异常重复提交 改变金额 ---> 判断是否已生成交易订单流水号
        String chargeNo = (String) switchMap.get("agentBillNo");
        Boolean isTransExit = transFlowService.isTransExit(chargeNo);
        if (isTransExit) {
            return "success";
        }
        userAccountService.rechargeNotify(switchMap);
        return "success";
    }

}

